package com.hupo.dyapp_01.controller;


import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("demo")
public class DemoController {

   @RequestMapping("upload")
    public String upload(@RequestBody byte[] file,String fileName) throws IOException {
       System.out.println("文件名："+fileName+",文件大小："+file.length+"字节");

       FileOutputStream fileOutputStream = new FileOutputStream("D:/upload/"+fileName);
       fileOutputStream.write(file);
       fileOutputStream.close();

       return "成功";
   }

   @GetMapping("file/{fileName}")
   public void show(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
      //I流
      FileInputStream fileinputStream = new FileInputStream("D:/upload/"+fileName);
      //O流
      ServletOutputStream outputStream = response.getOutputStream();

      //告诉客户端这是一个图片文件，不要启用下载
      response.setContentType("image/jpeg");

      //IO读写
      byte[] data = new byte[1024];
      int len = 0;
      while((len = fileinputStream.read(data)) != -1){
         outputStream.write(data,0,len);
      }
      //刷新
      outputStream.flush();
      //关闭
      outputStream.close();
      fileinputStream.close();
   }
}








